/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package queenb.web.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

import java.sql.Timestamp;
import java.util.Calendar;
//import org.hibernate.lob.SerializableClob;
import org.apache.log4j.Logger;
import queenb.net.datacontrol.Param;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.util.*;
import org.richfaces.model.UploadItem;
import queenb.web.bean.FileDescription;

/**
 *
 * @author thanhct
 */
public class Util {

    private static final Logger logger = Logger.getLogger(Util.class);
    public static final int MODULE_PROJECT = 3;
    public static final String DATE_PATTERN = "dd/MM/yyyy";
    public static final String DATE_PATTERN1 = "yyyy/MM/dd";
    public static final String DATE_TIME_PATTERN = "dd/MM/yyyy HH:mm";

    public static java.sql.Date stringToSQLDate(String str, String pattern) throws ParseException {
        if (str == null || str.trim().equals("")) {
            return null;
        }

        DateFormat formater = new SimpleDateFormat(pattern);
        java.util.Date parsedUtilDate = formater.parse(str);
        return toSQLDate(parsedUtilDate);

    }

    public static String toVnShortDate(Object object, String pattern) throws ParseException {
        DateFormat df = new SimpleDateFormat(pattern);
        return df.format(object);
    }

    public static String parseDateY(String strday, String dayformat) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");

        Date date;
        String dateformat = "";
        try {
            date = sdf.parse(strday);
            sdf.applyPattern(dayformat);
            dateformat = sdf.format(date);
            return dateformat;
        } catch (ParseException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return "";
        }

    }

    public static String toVnShortDate1(Object object, String pattern) throws ParseException {
        return toVnShortDate(object, pattern).replaceAll("/", "");
    }

    public static boolean parseBoolean(Object object) {
        if (parseInt(object) == 0) {
            return false;
        }
        return true;
    }

    public static int parseBoolToInt(Boolean b) {
        if (b == true) {
            return 1;
        } else {
            return 0;
        }
    }

    public static int parseInt(Object object) {
        if (object == null) {
            return 0;
        } else {
            return Integer.parseInt(parseString(object));
        }
    }

    public static Date toVnDate(Object object, String pattern) throws ParseException {
        if (object == null) {
            return null;
        }
        DateFormat df = new SimpleDateFormat(pattern);
        return df.parse(toVnShortDate(object, pattern));
    }

    public static java.sql.Date toSQLDate(Date date) {
        if (date == null) {
            return null;
        } else {
            return new java.sql.Date(date.getTime());
        }
    }

    public static java.sql.Date toSQLDate(String date, String pattern) throws ParseException {
        if (date == null) {
            return null;
        } else {
            DateFormat df = new SimpleDateFormat(pattern);
            return new java.sql.Date(df.parse(date).getTime());
        }
    }

    public static Timestamp toTimestamp(Date date) {
        if (date == null) {
            return null;
        } else {
            return new Timestamp(date.getTime());
        }

    }

    public static Timestamp hourToTimestamp(String hourMinute) {
        Timestamp timestamp = null;
        if (hourMinute != null && !hourMinute.trim().equals("")) {
            String[] hourMinuteSplit = hourMinute.split(":");
            Calendar cl = Calendar.getInstance();
            cl.set(Calendar.HOUR_OF_DAY, Integer.parseInt(hourMinuteSplit[0]));
            cl.set(Calendar.MINUTE, Integer.parseInt(hourMinuteSplit[1]));
            timestamp = new Timestamp(cl.getTimeInMillis());
        }
        return timestamp;
    }

    public static Timestamp convertStringToTimerTamp(String time, String patterns) throws ParseException {
        SimpleDateFormat dateFormat = new SimpleDateFormat(patterns);
        java.util.Date parsedDate = dateFormat.parse(time);
        Timestamp timeTamp = new Timestamp(parsedDate.getTime());
        return timeTamp;
    }

    public static Timestamp convertDateHour(String time) {
        java.util.Date dateU = new Date();
        long time1 = dateU.parse(time);
        java.sql.Timestamp timeStamp = new Timestamp(time1);
        return timeStamp;
    }

    public static Date parseDate(Date date, String pattern) throws ParseException {
        if (date == null) {
            return null;
        }

        return date;

    }

    public static Date parseDate(String date, String pattern) throws ParseException {
        if (date == null) {
            return null;
        }
        String day = date.replace(".", "/");
        DateFormat df = new SimpleDateFormat(pattern);
        return (Date) df.parse(day);
    }

    public static String parseString(Object object) {
        return object == null ? "" : object.toString().trim();
    }

    public static String convertMD5(String arg) {
        String hashed_key = "";
        try {
            byte[] intext = arg.getBytes();
            StringBuffer sb = new StringBuffer();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            byte[] md5rslt = md5.digest(intext);
            for (int i = 0; i < md5rslt.length; i++) {
                sb.append(String.format("%02x", 0xff & md5rslt[i]));
            }
            hashed_key = sb.toString();
        } catch (Exception e2) {
            System.out.println(e2);
        }
        return hashed_key;
    }

    public static boolean contains(String String, String searchStr) {

        if (String.indexOf(searchStr) != -1) {
            return true;
        } else {
            return false;
        }

    }

    public Date String2Date(String date, String format) {
        DateFormat df = new SimpleDateFormat(format);
        Date result = new Date();
        try {
            result = df.parse(date);

        } catch (ParseException e) {
            e.printStackTrace();
        }
        return result;
    }
//Thanh Luan Create

    public static String numberformater(int num) {
        NumberFormat format = new DecimalFormat("##000");
        return format.format(num);
    }

    public static String numberformater(double num, String pattern) {
        NumberFormat format = new DecimalFormat(pattern);
        return format.format(num);
    }

    public static String connectString(String st, String strSplit) {
        try {
            StringTokenizer tokenizer = new StringTokenizer(st, strSplit);
            String stconnect = "";
            while (tokenizer.hasMoreTokens()) {
                String stc = tokenizer.nextToken();
                stconnect += stc;
            }
            return stconnect;
        } catch (Exception ex) {
            return null;
        }

    }

    public static Double convertStringToDouble(String st) {
        try {
            double d = 0;
            String stConvert = connectString(st, ",");
            if (stConvert != null) {
                d = Double.valueOf(stConvert).doubleValue();
            }
            return d;
        } catch (Exception ex) {
            return 0.0;
        }

    }
//Thanh Luan end

    public static void printDebug(Param[] p, Logger logger) {
        logger.debug("so luong parameters::" + p.length);
        for (int i = 0; i < p.length; i++) {
            logger.info(p[i].toString());
        }
    }// upload file

    public static FileDescription saveFile(UploadItem item) throws IOException {
        File fromFile = new File(item.getFile().getPath());
        logger.debug("current temp file:" + item.getFile());
        File toFile = new File(ResourcesProvider.getUploadFolder() + Util.createGUID() + "_" + item.getFileName().replaceAll(" ", ""));
        copy(fromFile, toFile);
        FileDescription fileDescription = new FileDescription();
        fileDescription.setFileName(item.getFileName());
        fileDescription.setNewName(toFile.getName());
        fileDescription.setFileMime(getFileExtension(toFile.getName()));
        return fileDescription;
    }
    
    public static FileDescription saveFileTour(UploadItem item) throws IOException {
        File fromFile = new File(item.getFile().getPath());
        logger.debug("current temp file:" + item.getFile());
        File toFile = new File(ResourcesProvider.getUploadFolderTour() + Util.createGUID() + "_" + item.getFileName().replaceAll(" ", ""));
        copy(fromFile, toFile);
        FileDescription fileDescription = new FileDescription();
        fileDescription.setFileName(item.getFileName());
        fileDescription.setNewName(toFile.getName());
        fileDescription.setFileMime(getFileExtension(toFile.getName()));
        return fileDescription;
    }

    private static String getFileExtension(String fileName) {
        return fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
    }

    public static String createGUID() {
        return UUID.randomUUID().toString();
    }

    public static void copy(File fromFile, File toFile) throws IOException {
        if (!fromFile.exists()) {
            throw new IOException("FileCopy: " + "no such source file: "
                    + fromFile.getName());
        }
        if (!fromFile.isFile()) {
            throw new IOException("FileCopy: " + "can't copy directory: "
                    + fromFile.getName());
        }
        if (!fromFile.canRead()) {
            throw new IOException("FileCopy: " + "source file is unreadable: "
                    + fromFile.getName());
        }

        if (toFile.isDirectory()) {
            toFile = new File(toFile, fromFile.getName());
        }

        if (toFile.exists()) {
            if (!toFile.canWrite()) {
                throw new IOException("FileCopy: "
                        + "destination file is unwriteable: " + toFile.getName());
            }
            System.out.print("Overwrite existing file " + toFile.getName()
                    + "? (Y/N): ");
            System.out.flush();
            BufferedReader in = new BufferedReader(new InputStreamReader(
                    System.in));
            String response = in.readLine();
            if (!response.equals("Y") && !response.equals("y")) {
                throw new IOException("FileCopy: "
                        + "existing file was not overwritten.");
            }
        } else {
            String parent = toFile.getParent();
            if (parent == null) {
                parent = System.getProperty("user.dir");
            }
            File dir = new File(parent);
            if (!dir.exists()) {
                throw new IOException("FileCopy: "
                        + "destination directory doesn't exist: " + parent);
            }
            if (dir.isFile()) {
                throw new IOException("FileCopy: "
                        + "destination is not a directory: " + parent);
            }
            if (!dir.canWrite()) {
                throw new IOException("FileCopy: "
                        + "destination directory is unwriteable: " + parent);
            }
        }

        FileInputStream from = null;
        FileOutputStream to = null;
        try {
            from = new FileInputStream(fromFile);
            to = new FileOutputStream(toFile);
            byte[] buffer = new byte[4096];
            int bytesRead;

            while ((bytesRead = from.read(buffer)) != -1) {
                to.write(buffer, 0, bytesRead); // write
            }
        } finally {
            if (from != null) {
                try {
                    from.close();
                } catch (IOException e) {
                }
            }
            if (to != null) {
                try {
                    to.close();
                } catch (IOException e) {
                }
            }
        }
    }
    // bo dau tieng viet
    private static char[] SPECIAL_CHARACTERS = {
        'À', 'Á', 'Â', 'Ã', 'È', 'É', 'Ê', 'Ì', 'Í', 'Ò',
        'Ó', 'Ô', 'Õ', 'Ù', 'Ú', 'Ý', 'à', 'á', 'â', 'ã', 'è', 'é', 'ê',
        'ì', 'í', 'ò', 'ó', 'ô', 'õ', 'ù', 'ú', 'ý', 'Ă', 'ă', 'Đ', 'đ',
        'Ĩ', 'ĩ', 'Ũ', 'ũ', 'Ơ', 'ơ', 'Ư', 'ư', 'Ạ', 'ạ', 'Ả', 'ả', 'Ấ',
        'ấ', 'Ầ', 'ầ', 'Ẩ', 'ẩ', 'Ẫ', 'ẫ', 'Ậ', 'ậ', 'Ắ', 'ắ', 'Ằ', 'ằ',
        'Ẳ', 'ẳ', 'Ẵ', 'ẵ', 'Ặ', 'ặ', 'Ẹ', 'ẹ', 'Ẻ', 'ẻ', 'Ẽ', 'ẽ', 'Ế',
        'ế', 'Ề', 'ề', 'Ể', 'ể', 'Ễ', 'ễ', 'Ệ', 'ệ', 'Ỉ', 'ỉ', 'Ị', 'ị',
        'Ọ', 'ọ', 'Ỏ', 'ỏ', 'Ố', 'ố', 'Ồ', 'ồ', 'Ổ', 'ổ', 'Ỗ', 'ỗ', 'Ộ',
        'ộ', 'Ớ', 'ớ', 'Ờ', 'ờ', 'Ở', 'ở', 'Ỡ', 'ỡ', 'Ợ', 'ợ', 'Ụ', 'ụ',
        'Ủ', 'ủ', 'Ứ', 'ứ', 'Ừ', 'ừ', 'Ử', 'ử', 'Ữ', 'ữ', 'Ự', 'ự',};
    private static char[] REPLACEMENTS = {
        'A', 'A', 'A', 'A', 'E', 'E', 'E',
        'I', 'I', 'O', 'O', 'O', 'O', 'U', 'U', 'Y', 'a', 'a', 'a', 'a',
        'e', 'e', 'e', 'i', 'i', 'o', 'o', 'o', 'o', 'u', 'u', 'y', 'A',
        'a', 'D', 'd', 'I', 'i', 'U', 'u', 'O', 'o', 'U', 'u', 'A', 'a',
        'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A',
        'a', 'A', 'a', 'A', 'a', 'A', 'a', 'A', 'a', 'E', 'e', 'E', 'e',
        'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'E', 'e', 'I',
        'i', 'I', 'i', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o',
        'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O', 'o', 'O',
        'o', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u', 'U', 'u',
        'U', 'u',};

    public static String UnUnicode(String s) {
        if (s != null) {
            StringBuilder sb = new StringBuilder(s);
            for (int i = 0; i < sb.length(); i++) {
                sb.setCharAt(i, removeAccent(sb.charAt(i)));
            }
            return sb.toString();
        } else {
            return null;
        }
    }

    public static char removeAccent(char ch) {
        int index = Arrays.binarySearch(SPECIAL_CHARACTERS, ch);
        if (index >= 0) {
            ch = REPLACEMENTS[index];
        }
        return ch;
    }
    //

    public static void saveFileCSV(UploadItem item) throws IOException {
        File fromFile = new File(item.getFile().getPath());
        logger.debug("current temp file:" + item.getFile());
        File toFile = new File("D://SGT-QUEENB//upload//import.csv");
        //File toFile = new File(ResourcesProvider.getImporttExcel() + "import.xls");
        if (toFile.exists()) {
            toFile.delete();
            toFile = new File("D://SGT-QUEENB//upload//import.csv");
            //toFile = new File(ResourcesProvider.getImporttExcel() + "import.xls");
        }
        copy(fromFile, toFile);
    }

    public static void saveFileXLS(UploadItem item) throws IOException {
        File fromFile = new File(item.getFile().getPath());
        logger.debug("current temp file:" + item.getFile());
        File toFile = new File("D://SGT-QUEENB//upload//import.xls");
        //File toFile = new File(ResourcesProvider.getImporttExcel() + "import.xls");
        if (toFile.exists()) {
            toFile.delete();
            toFile = new File("D://SGT-QUEENB//upload//import.xls");
            //toFile = new File(ResourcesProvider.getImporttExcel() + "import.xls");
        }
        copy(fromFile, toFile);
    }
public static String getCodeTour(String stringToModify) {
        int indexOfFind = stringToModify.indexOf(stringToModify);
        if (indexOfFind < 0) {
            return stringToModify;
        }

        StringBuffer oldStringBuffer = new StringBuffer(stringToModify);
        StringBuffer newStringBuffer = new StringBuffer();
        int i = 0;
        int length = oldStringBuffer.length();
        boolean check = false;

        while (i < length) {
            char c = oldStringBuffer.charAt(i);
            if (c == '[') {
                check = true;
                i++;
                continue;
            }
            if (c == ']') {
                check = false;
                i++;
                continue;
            }
            if (check) {
                newStringBuffer.append(c);
            }
            i++;
        }


        return new String(newStringBuffer);
    }

    public static String removeQuotes(String stringToModify) {
        int indexOfFind = stringToModify.indexOf(stringToModify);
        if (indexOfFind < 0) {
            return stringToModify;
        }

        StringBuffer oldStringBuffer = new StringBuffer(stringToModify);
        StringBuffer newStringBuffer = new StringBuffer();
//        for (int i = 0, length = oldStringBuffer.length(); i < length; i++) {
//            char c = oldStringBuffer.charAt(i);
//            if (c == '"' || c == '\'') {
//                // do nothing
//            } else {
//                newStringBuffer.append(c);
//            }
//
//        }
        int i = 0;
        int length = oldStringBuffer.length();
        boolean check = false;

        while (i < length) {
            char c = oldStringBuffer.charAt(i);
            if (c == '<') {
                check = true;
                i++;
                continue;
            }
            if (check) {
                newStringBuffer.append(c);
            }
            i++;
        }

        if (!check) {
            int j = 0;
            while (j < length) {
                char c = oldStringBuffer.charAt(j);
                newStringBuffer.append(c);
                j++;
            }
        }
        int lengthNew = newStringBuffer.length();
        if (newStringBuffer.charAt(lengthNew - 1) == '>') {
            newStringBuffer.setCharAt(lengthNew - 1, ' ');
        }

        return new String(newStringBuffer);
    }
    
}
